package com.csdj.t309.papermanage.controller;

import com.csdj.t309.papermanage.entity.User;
import com.csdj.t309.papermanage.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class UserController {

    @Resource
    private UserService userService;
    private Logger log = LoggerFactory.getLogger("UserController");

    private User user;

    PrintWriter writer = null;

    @GetMapping("login")
    public String login(){
        return "login";
    }

    @PostMapping("/doLogin")
    public String login(@RequestParam(value = "account",required = false) String account,
                        @RequestParam(value = "password",required = false) String password,
                        HttpServletRequest request,
                        HttpServletResponse response,
                        HttpSession session, Model model) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        session = request.getSession();
        writer = response.getWriter();
        user = userService.login(account,password);
        if(user==null){
            writer.println("<script>alert('用户名或密码错误')</script>");
            return "login";
        }else{
            session.setAttribute("user",user);
            model.addAttribute("userName",user.getUsername());
            writer.println("<script>alert('登录成功')</script>");
            return "main";
        }
    }
}
